package com.liveinstars.common.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.Map;
import java.util.stream.Stream;

/**
 * Created by guoyanjiang on 2018/4/19.
 */
public class CacheUtil {

    public static final String KEY_PREFIX_VIEW_COUNT = "view_count_";
    public static final String TOTAL_COIN_COUNT = "coin_total_configuration";
    public static final String IM_MESSAGE_ID = "im_message_id";
    public static final String IM_USER_UUID_LIST = "im_user_uuid_list";
    public static final String IM_USER_MESSAGE_LIST = "im_user_message_list";
    public static final String IM_USER_TOKEN_CHATSERVER_LIST = "im_user_token_chatserver_list";
    public static final String IM_USERINFO = "im_userinfo";
    public static final String CHATGROUP_LIST = "CHATGROUP_LIST";
    public static final String TOP_COIN_LIST_COIN_PAIR_DAY_RECORDS = "TopCoinList_CoinPairDayRecords";
    public static final String TOP_COIN_LIST = "TopCoinList";

    public static String getCacheKey(Map<String, Object> map) {
        StringBuilder builder = new StringBuilder();
        map.entrySet().forEach(entry -> {
            builder.append("&" + entry.getKey() + "=");
            builder.append(entry.getValue() != null ? entry.getValue() : "");
        });
        return changeHashIfNeed(builder.toString());
    }

    public static String getCacheKey(Object[] params) {
        StringBuilder builder = new StringBuilder();
        Stream.of(params)
                .filter(obj -> obj != null)
                .forEach(obj -> {
                    String feature = obj instanceof String ? obj.toString() : JSON.toJSONString(obj);
                    builder.append(changeHashIfNeed(feature));
                });
        return builder.toString();
    }

    private static String changeHashIfNeed(String context) {
        if (isChinese(context) || context.length() > 100) {
            return DigestUtils.sha1Hex(context);
        }
        return context;
    }

    // 判断一个字符是否是中文
    private static boolean isChinese(char ch) {
        //获取此字符的UniCodeBlock
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(ch);
        //  GENERAL_PUNCTUATION 判断中文的“号
        //  CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号
        //  HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的，号
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    // 判断一个字符串是否含有中文
    public static boolean isChinese(String str) {
        if (str == null) {
            return false;
        }
        for (char c : str.toCharArray()) {
            if (isChinese(c)) {
                return true;// 有一个中文字符就返回
            }
        }
        return false;
    }

    public static String getSearchBannerDataMappingKey() {
        return "search_banner_data";
    }

    public static String getHoldAccessTokenKey() {
        return "hold_access_token";
    }

    public static String getHoldRefreshTokenKey() {
        return "hold_refresh_token";
    }

    public static String getActivityDrawTimeModelKey(Long uid, Long activityId) {
        return String.format("app_activity_%d_draw_time_model_%d", activityId, uid);
    }

    public static String getTokenIconsKeyForApp() {
        return "token_icons";
    }

    public static String getTokenIconsKeyForWeb() {
        return "token_icons_web";
    }

    //指数需要保存redis，列表从数据库中获取放入内存缓存，列表从api获取的放入redis缓存，用来循环获取行情和权重，表现等数据
    //指数行情第一次获取n天数据保存入数据库，然后从数据库获取第一页数据放入redis
    public static String getIndexListKey() {
        return "index_coin_list";
    }

    public static String get8BTCIndexRebaseValueKey() {
        return "index8btc_rebase_value";
    }

    public static String get8BTCVIIndexRebaseValueKey() {
        return "index8btcvi_rebase_value";
    }

    public static String getWeixinRankingKey() {
        return "weixin_ranking";
    }

    public static String get8BTCIndexWeightKey() {
        return "index8btc_weight";
    }

    public static String getIndexTickKey(String cid, String period) {
        return String.format("index_coin_ticket_%s_%s", cid, period);
    }

    public static String getCoinLastBigTransferTime(String cid) {
        return "coin_lastbigtransfertime" + cid;
    }

    public static String get24HighPriceByCoinKey(String coinKey) {
        return String.format("coin_24Highprice_%s", coinKey);
    }

    public static String get24LowPriceByCoinKey(String coinKey) {
        return String.format("coin_24Lowprice_%s", coinKey);
    }

    //24小时振幅
    public static String get24AmplitudeKey() {
        return String.format("coin_24Amplitude");
    }

    //===== 资讯
    public static String getPrefixViewCountKey(Long newsId) {
        return KEY_PREFIX_VIEW_COUNT + newsId;
    }

    //===== 金币任务
    public static String getGoldTaskSignKey(Long uid) {
        return "gold_sign_" + uid;
    }

    public static String getGoldDayTaskStatusKey(Long uid) {
        return "gold_day_task_" + uid;
    }

    public static String getGoldDayScratchKey(Long uid) {
        return "gold_day_scratch_" + uid;
    }

    public static String getMessageKey(String md5) {
        return "message_" + md5;
    }

    public static String getWarningHisCacheKey(Long uid) {
        return "warning_push_" + uid;
    }

    //===== 通用

    public static String getTickerRateKey() {
        return "ticker_rate";
    }

    //矿机排行
    public static String getWebMillRankKey() {
        return "web_mill_rank_market";
    }

    //破发率
    public static String getExchangeBleakRateKey() {
        return "exchange_bleak_rate";
    }

    //挖矿数据监测
    public static String getDigDataMonitorKey() {
        return "web_dig_data_monitor";
    }

    //全网算力趋势
    public static String getNetCalculateForceKey() {
        return "web_net_calculate_force";
    }

    //算力分布图
    public static String getCalPowerDistributKey() {
        return "web_call_power_Distribut";
    }

    //eth区块奖励
    public static String getEthCoinbaseRewardKey() {
        return "web_eth_coinbase_reward";
    }

    //最新出块
    public static String getRecentlyPieceKey() {
        return "web_recently_piece";
    }

    //钱包排行缓存key
    public static String getWalletRankListKey() {
        return "WALLET_RANKING_LIST";
    }

    public static String getIMMsgID() {
        return IM_MESSAGE_ID;
    }

    public static String getIMUserUUIDList(Integer userid) {
        return IM_USER_UUID_LIST + userid;
    }

    public static String getIMUserMessageList(Integer userid) {
        return IM_USER_MESSAGE_LIST + userid;
    }

    public static String getImUserTokenChatserverList(Integer userid) {
        return IM_USER_TOKEN_CHATSERVER_LIST + userid;
    }

    public static String getImUserInfo(int userId) {
        return IM_USERINFO + userId;
    }

    public static String get8BTCIndexRebaseSymbolPriceKey() {
        return "index8btc_rebase_symbol_price";
    }

    public static String get8BTCVIIndexRebaseSymbolPriceKey() {
        return "index8btcvi_rebase_symbol_price";
    }

    public static String getBadWordListCache() {
        return "badwordlistcache";

    }

    public static String getAddChatgroupDate() {
        return "addchatgroupdate";
    }

    public static String getShieldUserVote() {
        return "shieluservote";
    }
}
